<template>
  <div>
    <my-header
      ><el-breadcrumb-item>积分商城</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item></my-header
    >

    <!-- 卡片视图区域 -->
    <el-card class="box-card">
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="7"
          ><!-- 输入框 -->
          <el-input
            placeholder="请输入商品名称"
            v-model="inputValue"
            clearable
            @clear="getGoodList"
          >
            <template #append>
              <el-button icon="Search" @click="onSearchList" />
            </template> </el-input
        ></el-col>
        <el-col :span="4"
          ><el-button type="primary" @click="addDialogVisible = true">添加商品</el-button></el-col
        >
      </el-row>

      <!-- 商品列表区域 -->
      <el-table :data="goodlist" style="width: 100%" border stripe>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="name" label="商品名称"></el-table-column>
        <el-table-column prop="price" label="积分" sortable></el-table-column>
        <el-table-column prop="pic" label="图片">
          <template #default="scope">
            <el-image
              style="width: 60px; height: 60px"
              :src="'http://192.168.101.65:9000' + scope.row.pic"
              :fit="fit"
            />
          </template>
        </el-table-column>
        <el-table-column prop="sold" label="已售"></el-table-column>
        <el-table-column prop="stock" label="库存" sortable></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column label="商品在售/停售">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="1"
              inactive-value="0"
              inline-prompt
              active-text="在售"
              inactive-text="停售"
              @change="goodStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="Edit"
              size="small"
              @click="showEditDialog(scope.row.id)"
            />
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="Delete"
              size="small"
              @click="removeGoodById(scope.row.id)"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        :page-sizes="[1, 2, 5, 10]"
        small="small"
        background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="goodlist.length"
      />
    </el-card>

    <!-- 添加商品的对话框 -->
    <el-dialog v-model="addDialogVisible" title="添加商品" width="50%" @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form
        ref="addFormRef"
        :model="addForm"
        status-icon
        :rules="addFormRules"
        label-width="80px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="addForm.name" />
        </el-form-item>
        <el-form-item label="积分" prop="price">
          <el-input v-model="addForm.price" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="addForm.stock" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="addForm.remark" />
        </el-form-item>
        <el-form-item label="图片" prop="pic">
          <el-upload
            list-type="picture-card"
            :limit="1"
            show-file-list
            :auto-upload="false"
            :on-change="changePic"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addGood">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改商品的对话框 -->
    <el-dialog v-model="editDialogVisible" title="修改商品" width="50%" @close="editDialogClosed">
      <!-- 内容主体区域 -->
      <el-form
        ref="editFormRef"
        :model="editForm"
        status-icon
        :rules="editFormRules"
        label-width="70px"
      >
        <el-form-item label="商品名称" prop="name">
          <el-input v-model="editForm.name" disabled />
        </el-form-item>
        <el-form-item label="积分" prop="price">
          <el-input v-model="editForm.price" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input v-model="editForm.stock" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="editForm.remark" />
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editGoodInfo">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import { GoodList, addGood, updateGood, updateGoodStatus } from '../../api/good.js'
export default {
  data() {
    // 验证积分的正则表达式
    const checkPoint = (rule, value, cb) => {
      const regPoint = /^([1-9][0-9]|[1-9][0-9][0-9]|1000)$/
      if (regPoint.test(value)) {
        return cb()
      }
      cb(new Error('注意：积分范围在 10 ~ 1000 的正整数！'))
    }
    const checkStock = (rule, value, cb) => {
      if (isNaN(value)) {
        cb(new Error('请正确输入合法的数字！'))
      }
    }
    return {
      inputValue: '',
      goodlist: [],
      // 控制添加商品对话框的显示与隐藏
      addDialogVisible: false,
      // 控制修改商品对话框的显示与隐藏
      editDialogVisible: false,
      // 添加商品的表单数据
      addForm: { name: '', price: '', sold: '', stock: '', remark: '' },
      // 添加表单的验证规则对象
      addFormRules: {
        name: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '商品名称的长度在2~10个字符之间', trigger: 'blur' }
        ],
        point: [
          { required: true, message: '请输入积分', trigger: 'blur' },
          { validator: checkPoint, trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '请输入库存', trigger: 'blur' },
          { validator: checkStock, trigger: 'blur' }
        ],
        remark: [{ required: true, message: '请输入备注', trigger: 'blur' }]
      },
      // 查询到的商品信息
      editForm: {},
      // 修改表单的验证规则对象
      editFormRules: {
        price: [
          { required: true, message: '请输入积分', trigger: 'blur' },
          { validator: checkPoint, trigger: 'blur' }
        ],
        stock: [
          { required: true, message: '请输入库存', trigger: 'blur' },
          { validator: checkStock, trigger: 'blur' }
        ],
        remark: [{ required: true, message: '请输入备注', trigger: 'blur' }]
      },
      formData: ''
    }
  },
  created() {
    this.getGoodList()
  },
  methods: {
    changePic(file) {
      console.log(file)
      this.formData = new FormData()
      this.formData.append('filedate', file.raw)
    },
    onSearchList() {
      this.goodlist = this.goodlist.filter((item) => item.name.includes(this.inputValue))
    },
    async getGoodList() {
      const { data: res } = await GoodList()
      if (res.code !== 1) {
        return this.$message.error('获取商品列表失败')
      }
      this.goodlist = res.data.items
    },
    // 监听 switch 开关状态的改变
    async goodStateChanged(goodinfo) {
      const { data: res } = await updateGoodStatus({ shopId: goodinfo.id, status: goodinfo.status })
      if (res.code !== 1) {
        this.getGoodList()
        return this.$message.error('更新商品状态失败！')
      } else {
        setTimeout(() => {
          this.getGoodList()
        }, 1000)
        this.$message.success('更新商品状态成功！')
      }
    },
    // 监听添加商品对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击按钮，添加新商品
    async addGood() {
      const params = {
        name: this.addForm.name,
        price: this.addForm.price,
        remark: this.addForm.remark,
        stock: this.addForm.stock,
        filedata: this.formData
      }
      const { data: res } = await addGood(params)
      if (res.code !== 1) {
        this.$message.error('添加商品失败！')
      }
      // 隐藏添加商品的对话框
      this.$message.success('添加商品成功！')
      // 重新获取商品列表数据
      this.addDialogVisible = false
      setTimeout(() => {
        this.getGoodList()
      }, 1000)
    },
    // 展示编辑商品的对话框
    async showEditDialog(id) {
      // 获取该商品信息
      this.editForm = this.goodlist.find((item) => item.id === id)
      this.editDialogVisible = true
    },
    // 监听修改商品对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改商品信息并提交
    async editGoodInfo() {
      const { data: res } = await updateGood(this.editForm)
      if (res.code !== 1) {
        return this.$message.error('更新商品信息失败！')
      }
      setTimeout(() => {
        this.getGoodList()
      }, 1000)
      // 关闭对话框
      this.editDialogVisible = false
      // 提示修改成功
      this.$message.success('更新商品信息成功！')
    },
    // 根据id删除对应的商品信息
    async removeGoodById(id) {
      // 弹框询问商品是否删除数据
      const confirmResult = await this.$confirm('此操作将永久删除该商品，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => {
        return err
      })
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await axios.delete(`/content/shop/delete/${id}`)
      if (res.code !== 1) {
        return this.$message.error('删除商品失败！')
      }
      setTimeout(() => {
        this.getGoodList()
      }, 1000)
      this.$message.success('删除成功！')
    }
  }
}
</script>

<style lang="less" scoped></style>
